/*
 *  Simple command line parser for ECE 275
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 1024

/* Arguments struct */
struct args_t {
  int argc;
  char **argv;
} args_s;

/* Global Variables */
struct args_t *Args = &args_s;
char *Usage_message;

/* Functions */
void usage_message();

int main(int argc, char ** argv) 
{
  Args->argc = argc;
  Args->argv = argv;
  usage_message();

  #ifdef DEBUG
    printf("Args->argv[0]: %s\nArgs->argv[1]: %s\nArgs->argv[2]: %s\n",
      *(Args->argv+0), *(Args->argv+1), *(Args->argv+2));
  #endif

  if (argc < 2) {
    printf("%s", Usage_message);
    exit(-1);
  }

  #ifdef DEBUG
    printf("argv[0] = %s\nargv[1] = %s\nargv[2] = %s\n", 
      *(argv+0), *(argv+1), *(argv+2));
  #endif

  /* Flip arguments in struct if specified
   * in an incorrect order */
  if (*(*(argv+1)+0) != '-' && 
      *(*(argv+2)+0) == '-' ) {
    Args->argv[2] = argv[1];
    Args->argv[1] = argv[2];
    #ifdef DEBUG
      printf("Argument 1 NOT an option. Flipping...\n");
      printf("Flipped argument: %s\n", *(Args->argv+1));
      printf("Flipped file: %s\n", *(Args->argv+2));
    #endif
  }

  free(Usage_message);
  return EXIT_SUCCESS;
}


void usage_message() 
{
  int count;
  Usage_message = (char *) malloc(sizeof(char) * BUFFERSIZE);
  count = sprintf(Usage_message, "usage: %s [OPTION] [FILE]\n", *(Args->argv+0));
  #ifdef DEBUG
    printf("Usage_message: %p\n", Usage_message);
    printf("Usage_message+count: %p\n", Usage_message + count);
  #endif
  sprintf(Usage_message + count, "options:\n\t--option1  --option2  --option3\n");
}
